// ZLEMA (Zero Lag Exponential Moving Average) 指标
// 用于 Zero Lag Trend Signals 策略

function calculateZLEMA (dataList, length = 70, mult = 1.2) {
  const result = []
  const lag = Math.floor((length - 1) / 2)
  const emaAlpha = 2 / (length + 1)
  const atrAlpha = 1 / length
  const atrWindow = Math.max(length * 3, length)
  const atrQueue = []

  let ema = null
  let atr = null
  let prevClose = dataList[0]?.close ?? 0

  for (let i = 0; i < dataList.length; i++) {
    const candle = dataList[i]
    const src = candle.close
    const lagSrc = i >= lag ? dataList[i - lag].close : src
    const adjusted = src + (src - lagSrc)
    ema = ema == null ? adjusted : (emaAlpha * adjusted + (1 - emaAlpha) * ema)

    const high = candle.high
    const low = candle.low
    const tr = Math.max(
      high - low,
      Math.abs(high - prevClose),
      Math.abs(low - prevClose)
    )
    prevClose = candle.close
    atr = atr == null ? tr : (atr + (tr - atr) * atrAlpha)
    atrQueue.push(atr)
    if (atrQueue.length > atrWindow) {
      atrQueue.shift()
    }
    const volatility = Math.max(...atrQueue) * mult

    let trend = 0
    if (i > 0) {
      const prevResult = result[i - 1]
      if (prevResult) {
        trend = prevResult.trend ?? 0
      }
    }
    if (candle.close > ema + volatility) {
      trend = 1
    } else if (candle.close < ema - volatility) {
      trend = -1
    }

    result.push({
      zlema: ema,
      upper: ema + volatility,
      lower: ema - volatility,
      volatility,
      trend
    })
  }

  return result
}

const zlemaIndicator = {
  name: 'ZLEMA',
  shortName: 'ZLEMA',
  calcParams: [70, 1.2],
  figures: [
    { key: 'zlema', title: 'ZLEMA: ', type: 'line' },
    { key: 'upper', title: 'Upper: ', type: 'line' },
    { key: 'lower', title: 'Lower: ', type: 'line' }
  ],
  calc: (dataList, indicator) => {
    const params = indicator.calcParams || [70, 1.2]
    return calculateZLEMA(dataList, params[0], params[1])
  },
  styles: (indicator, defaultStyles, figureKey, result) => {
    if (figureKey === 'zlema' && result?.trend !== undefined) {
      // 根据趋势着色：看涨绿色(#00ffbb)，看跌红色(#ff1100)
      return {
        ...defaultStyles,
        line: {
          ...defaultStyles.line,
          color: result.trend === 1 ? '#00ffbb' : '#ff1100',
          size: 2
        }
      }
    }
    if (figureKey === 'upper') {
      return {
        ...defaultStyles,
        line: {
          ...defaultStyles.line,
          color: '#ff1100',
          style: 'dashed'
        }
      }
    }
    if (figureKey === 'lower') {
      return {
        ...defaultStyles,
        line: {
          ...defaultStyles.line,
          color: '#00ffbb',
          style: 'dashed'
        }
      }
    }
    return defaultStyles
  }
}

export default zlemaIndicator
export { calculateZLEMA }

